import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, Spin } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { AuthProvider, useAuth } from './hooks/useAuth';
import Layout from './components/Layout';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import ArticleManagement from './pages/ArticleManagement';
import ExamManagement from './pages/ExamManagement';
import ExamQuestionManagement from './pages/ExamQuestionManagement';
import QuestionManagement from './pages/QuestionManagement';
import CertificateManagement from './pages/CertificateManagement';
import LeaderboardManagement from './pages/LeaderboardManagement';
import UserManagement from './pages/UserManagement';
import SystemSettings from './pages/SystemSettings';

// 受保护的路由组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { user, loading } = useAuth();

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh' 
      }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  return <Layout>{children}</Layout>;
};

const AppRoutes: React.FC = () => {
  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      <Route path="/dashboard" element={
        <ProtectedRoute>
          <Dashboard />
        </ProtectedRoute>
      } />
      <Route path="/articles" element={
        <ProtectedRoute>
          <ArticleManagement />
        </ProtectedRoute>
      } />
      <Route path="/exams" element={
        <ProtectedRoute>
          <ExamManagement />
        </ProtectedRoute>
      } />
      <Route path="/exams/:id/questions" element={
        <ProtectedRoute>
          <ExamQuestionManagement />
        </ProtectedRoute>
      } />
      <Route path="/questions" element={
        <ProtectedRoute>
          <QuestionManagement />
        </ProtectedRoute>
      } />
      <Route path="/certificates" element={
        <ProtectedRoute>
          <CertificateManagement />
        </ProtectedRoute>
      } />
      <Route path="/leaderboards" element={
        <ProtectedRoute>
          <LeaderboardManagement />
        </ProtectedRoute>
      } />
      <Route path="/users" element={
        <ProtectedRoute>
          <UserManagement />
        </ProtectedRoute>
      } />
      <Route path="/settings" element={
        <ProtectedRoute>
          <SystemSettings />
        </ProtectedRoute>
      } />
      <Route path="/" element={<Navigate to="/dashboard" replace />} />
    </Routes>
  );
};

const App: React.FC = () => {
  return (
    <ConfigProvider locale={zhCN}>
      <AuthProvider>
        <Router>
          <AppRoutes />
        </Router>
      </AuthProvider>
    </ConfigProvider>
  );
};

export default App; 